
import MD5 from 'crypto-js/md5';
import { message } from 'ant-design-vue';
import qs from 'qs';
// import axios from 'axios';

const baseUrl = import.meta.env.VITE_API

export const getToken = () => {
  return localStorage.getItem('token');
};

export const getAuth = () => {
  const token = getToken();
  return token ? 'Bearer ' + getToken() : '';
};

export const setToken = (token: string) => {
  localStorage.setItem('token', token);
};

export const getUser = () => {
  const user = localStorage.getItem('user');
  return user ? JSON.parse(user) : {};
};

export const setUser = (user: any) => {
  localStorage.setItem('user', JSON.stringify(user));
};

export const fetch = async(url: string, options: any) => {
  const res = await window.ipcRenderer.invoke('fetch', url, options);
  if (!res.data) {
    message.error(res.message || '未知错误');
  }
  console.log(url, options, res);
  return res
};

export const login = async(body: any) => {
  body.password = MD5(body.password).toString() + 'kftp';
  const res = await fetch(baseUrl + '/login', {
    method: 'post',
    headers: {
      "Content-Type": "application/json",
    },
    body,
  });
  if (res.data) {
    setToken(res.data.token);
    setUser(res.data);
  }
  return res;
};

export const getRegion = async() => {
  const res = await fetch(baseUrl + '/region', {});
  return res;
};

export const getLives = async(params: any) => {
  const qStr = qs.stringify(params)
  const res = await fetch(`${baseUrl}/lives?${qStr}`, {
    headers: {
      authorization: getAuth(),
    },
  });
  return res;
};

export const getLingjiQrcode = async() => {
  const res = await fetch('https://sso.douyin.com/get_qrcode?aid=408314', {
    method: 'get',
    headers: {
      Referer: 'https://livedata.douyin.com/', // required
    },
  });
  return res;
};

export const updateLingjiAuth = async(params: any) => {
  const qStr = qs.stringify(params)
  const res = await fetch(`${baseUrl}/douyin/lingji/updateAuth?${qStr}`, {});
  return res;
};

export const checkLingjiQrcode = async(params: any) => {
  const res = await fetch(`https://sso.douyin.com/check_qrconnect?aid=408314&token=${params.token}`, {
    headers: {
      Referer: 'https://livedata.douyin.com/',
    },
  });

  if (res.data?.status === '3') {
    await updateLingjiAuth({
      id: params.id,
      redirect_url: res.data.redirect_url
    })
  }
  return res;
};
